package com.chiaic.unittest.unit;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.text.NumberFormat;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Service
@Slf4j
public class countImpl implements countService {
    private ConcurrentHashMap<String, AtomicInteger> counter = new ConcurrentHashMap<>();

    private ConcurrentHashMap<String, AtomicInteger> perCounter = new ConcurrentHashMap<>();

    public countImpl() {
        log.info("Counter Start");
    }

    @Override
    public void initCounter(String name) {
        initCounter(name,false);

    }

    @Override
    public void initCounter(String name, Boolean countPerSec) {
        if(counter.get(name) == null){
            counter.put(name,new AtomicInteger(0));
        }
        if (countPerSec){
            if(perCounter.get(name) == null){
                perCounter.put(name,new AtomicInteger(0));
                perCounter.put(name+"_times",new AtomicInteger(1));
            }
        }

    }

    @Override
    public long getCount(String name) {
        return counter.get(name).get();
    }

    @Override
    public void cleanCount(String name) {
        counter.get(name).set(0);
    }


    @Override
    public long addCount(String name, int n ) {
        return counter.get(name).getAndAdd(n);
    }

    @Override
    public long add(String name) {
        return counter.get(name).addAndGet(1);
    }

    @Scheduled(cron = "* * * * * *")
    public void print(){
        log.info("===============Counter printf================");
        counter.forEach((name,count)->{
            if (perCounter.get(name) != null){

                int countNo = count.get();
                int times = perCounter.get(name+"_times").getAndIncrement();
                int perCount = perCounter.get(name).get();





                log.info("{}   {}   {}   {}",name,NumberFormat.getInstance().format(countNo),
                        NumberFormat.getInstance().format(countNo-perCount),
                        NumberFormat.getInstance().format((countNo)/times));
                perCounter.get(name).getAndSet(count.get());

            }else {
                log.info("{}   {}",name,NumberFormat.getInstance().format(count.get()));
            }


        });
        log.info("===============Counter over================");
    }
}
